import { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import {
  getChannelListCreator,
  setCurrentCreator,
} from './store/action/channel';
import { getNewsById } from './store/action/news';

export default function App() {
  const state = useSelector((state) => state.channel);
  // console.log(state);
  return (
    <>
      {/* 头部频道 */}
      <Header />
      {/* 文章列表 */}
      <Main />
    </>
  );
}
function Main() {
  const { current } = useSelector((state) => state.channel);
  const dispatch = useDispatch();
  useEffect(() => {
    // 3 useEffect监控current，current变化时触发异步action
    dispatch(getNewsById(current));
  }, [current, dispatch]);
  return (
    <div className="list">
      <div className="article_item">
        <h3 className="van-ellipsis">JVM堆 栈 方法区详解</h3>
        <div className="img_box">
          <img
            src="http://toutiao.itheima.net/resources/images/54.jpg"
            className="w100"
            alt=""
          />
        </div>
        <div className="info_box">
          <span>爱妃</span>
          <span>152评论</span>
          <span>2019-03-11 09:00:00</span>
        </div>
      </div>
      <div className="article_item">
        <h3 className="van-ellipsis">Maven 私服搭建</h3>
        <div className="img_box">
          <img
            src="http://toutiao.itheima.net/resources/images/12.jpg"
            className="w100"
            alt=""
          />
        </div>
        <div className="info_box">
          <span>爱妃</span>
          <span>156评论</span>
          <span>2019-03-11 09:00:00</span>
        </div>
      </div>
      <div className="article_item">
        <h3 className="van-ellipsis">React 深入系列４：组件的生命周期</h3>
        <div className="img_box">
          <img
            src="http://toutiao.itheima.net/resources/images/30.jpg"
            className="w100"
            alt=""
          />
        </div>
        <div className="info_box">
          <span>爱妃</span>
          <span>43评论</span>
          <span>2019-03-11 09:00:00</span>
        </div>
      </div>
    </div>
  );
}

function Header() {
  const dispatch = useDispatch();
  useEffect(() => {
    dispatch(getChannelListCreator());
  }, [dispatch]);
  const { list, current } = useSelector((state) => state.channel);
  return (
    <ul className="category">
      {list.map((item) => {
        return (
          <li
            onClick={() => dispatch(setCurrentCreator(item.id))}
            className={item.id === current ? 'select' : ''}
            key={item.id}
          >
            {item.name}
          </li>
        );
      })}
    </ul>
  );
}
